package com.yk.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yk.api.system.dto.AnnouncementDTO;
import com.yk.common.core.domain.BasePageQuery;
import com.yk.common.core.domain.PageResult;
import com.yk.common.core.domain.Result;
import com.yk.system.convert.AnnouncementConvert;
import com.yk.system.entity.Announcement;
import com.yk.system.service.AnnouncementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 公告 yk-system
 *
 * @author lmx
 * @since 2024-01-04
 */
@Api(tags = "公告")
@RestController
@RequestMapping("/announcement")
@RequiredArgsConstructor
public class AnnouncementController {

    private final AnnouncementService announcementService;
    private final AnnouncementConvert announcementConvert;

    @GetMapping("/getById/{id}")
    @ApiOperation("公告-查询单个")
    public Result<Announcement> getById(@PathVariable(value = "id") Long id) {
        return Result.data(announcementService.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation("公告-新增")
    public Result<Boolean> save(@RequestBody @Validated AnnouncementDTO dto) {
        return Result.data(announcementService.save(announcementConvert.dto2Entity(dto)));
    }

    @PostMapping("/update")
    @ApiOperation("公告-修改")
    public Result<Boolean> updateById(@RequestBody @Validated AnnouncementDTO dto) {
        return Result.data(announcementService.updateById(announcementConvert.dto2Entity(dto)));
    }

    @GetMapping("/deleteById/{id}")
    @ApiOperation("公告-删除")
    public Result<Boolean> deleteById(@PathVariable(value = "id") Long id) {
        return Result.data(announcementService.removeById(id));
    }

    @PostMapping("/list")
    @ApiOperation("公告-查询列表")
    public Result<List<Announcement>> list(@RequestBody AnnouncementDTO param) {
        LambdaQueryWrapper<Announcement> lambda = new QueryWrapper<Announcement>().lambda();
        buildCondition(lambda, param);
        return Result.data(announcementService.list(lambda));
    }

    @PostMapping("/sort")
    @ApiOperation("排序")
    public Result<Void> pageList(@RequestBody AnnouncementDTO dto) {
        Assert.notEmpty(dto.getIds(), "ids不能为空");
        LambdaQueryWrapper<Announcement> lambda = new QueryWrapper<Announcement>().lambda();
        lambda.in(Announcement::getId, dto.getIds());
        List<Announcement> list = announcementService.list(lambda);
        if (CollUtil.isEmpty(list)) {
            return Result.ok();
        }
        AtomicInteger i = new AtomicInteger(1);
        Map<Long, Announcement> map = list.stream()
                .collect(Collectors.toMap(Announcement::getId, Function.identity(), (oldValue, newValue) -> newValue));
        dto.getIds().forEach(it ->{
            Announcement announcement = map.get(it);
            announcement.setSort(i.getAndIncrement());
            announcementService.updateBatchById(list);
        });
        return Result.ok();
    }

    @PostMapping("/page")
    @ApiOperation("公告-分页查询")
    public PageResult<Announcement> page(@RequestBody BasePageQuery<AnnouncementDTO> pageParam) {
        AnnouncementDTO param = pageParam.getParam();
        LambdaQueryWrapper<Announcement> lambda = new QueryWrapper<Announcement>().lambda();
        buildCondition(lambda, param);
        IPage<Announcement> page = announcementService.page(new Page<>(pageParam.getPageNum(), pageParam.getPageSize()), lambda);
        return PageResult.success(page.getRecords(), page.getTotal());
    }

    /**
     * 构造查询条件
     */
    private void buildCondition(LambdaQueryWrapper<Announcement> lambda, AnnouncementDTO param) {
        lambda.eq(StrUtil.isNotEmpty(param.getStatus()), Announcement::getStatus, param.getStatus());
        lambda.orderByAsc(Announcement::getSort);
    }


}